namespace TfsReportRenderer
{
    using System.Collections.Generic;

    using Microsoft.TeamFoundation.TestManagement.Client;

    public static class TestSuiteHelper
    {
        public static List<ITestSuiteBase> GetTestSuiteRecursive(this IStaticTestSuite staticTestSuite)
        {
            // 1. Store results in the IStaticTestSuit list.
            var result = new List<ITestSuiteBase>();

            // 2. Store a stack of our TestSuite.
            var stack = new Stack<ITestSuiteBase>();

            // 3. Add Root Test Suite
            stack.Push(staticTestSuite);

            // 4. Continue while there are TestSuites to Process
            while (stack.Count > 0)
            {
                // A. Get top Suite
                var dir = stack.Pop();

                try
                {
                    // B. Add all TestSuite at this directory to the result List.
                    result.Add(dir);
                    
                    // only static suites can contain subsuites
                    var staticDir = dir as IStaticTestSuite;
                    if (staticDir != null) 
                    {
                        // C. Add all SubSuite at this TestSuite.
                        foreach (ITestSuiteBase ss in staticDir.SubSuites)
                        {
                            stack.Push(ss);
                        }
                    }
                }
                // ReSharper disable once EmptyGeneralCatchClause
                catch
                {
                    // D. Fails to open the test suite
                }
            }

            return result;
        }
    }
}